package com.lab.book.web.interceptor;
/**
import com.alibaba.fastjson.JSONObject;
import com.lab.book.common.base.Res;
import com.lab.book.common.base.ResRecordsFactory;
import com.lab.book.web.common.util.JwtHelper;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Slf4j
public class TokenInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private JwtHelper jwtHelper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        //String path = StringUtils.trimToEmpty(request.getRequestURI());
        String tokenFromHeader = StringUtils.trimToEmpty(request.getHeader("token"));
        if (StringUtils.isEmpty(tokenFromHeader)) {
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter pw = response.getWriter();

            Res res = ResRecordsFactory.getInstance().getEmptyRes();
            res.setCode(401);
            res.setMessage("没有传递Token");

            pw.write(JSONObject.toJSONString(res));
            pw.flush();
            pw.close();
            return false;
        }

        if (jwtHelper.validateToken(tokenFromHeader)) {
            Claims claims = jwtHelper.getClaimsFromToken(tokenFromHeader);
            return true;
        } else {
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter pw = response.getWriter();

            Res res = ResRecordsFactory.getInstance().getEmptyRes();
            res.setCode(401);
            res.setMessage("传递的Token不对");

            pw.write(JSONObject.toJSONString(res));
            pw.flush();
            pw.close();
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        //controller方法处理完毕后，调用此方法
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        //页面渲染完毕后调用此方法
    }
}
*/